package com.cy.model;

import com.cy.BasicModel;
import com.cy.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Page;

import java.util.ArrayList;
import java.util.List;

@TableBind(tableName="company", pkName = "id")
public class Company extends BasicModel<Company> {
    public static final Company dao = new Company();
    public static final String SELECT_ALL = "`id`,`name`,`company_category_id`,`address`,`remark`";

    @Override
    public Page<Company> paginate(Integer pageNumber, Integer pageSize, String select, Company model) {
        List<Object> paras = new ArrayList<>();
        StringBuffer sqlExceptSelectBuffer = new StringBuffer("FROM company c LEFT JOIN company_category cc ON c.company_category_id = cc.id WHERE 1=1");
        StringBuffer selectBuffer = new StringBuffer("SELECT ").append(select);

        pageNumber = pageNumber == null || pageNumber == 0 ? 1 : ++pageNumber;
        pageSize = pageSize == null || pageSize == 0 ? 20 : pageSize;

        if (model != null) {
            String[] attrNames = model.getAttrNames();
            for (String attrName : attrNames) {
                Object attrValue = model.get(attrName);
                if (attrValue != null) {
                    if(attrName.equals("name")) {
                        sqlExceptSelectBuffer.append(" AND c.name LIKE ? ");
                        attrValue = "%"+attrValue+"%";
                    } else {
                        sqlExceptSelectBuffer.append(" AND `" + attrName + "`=?");
                    }
                    paras.add(attrValue);
                }
            }
        }

        return paras.size() > 0 ? paginate(pageNumber, pageSize, selectBuffer.toString(), sqlExceptSelectBuffer.toString(), paras.toArray())
                                : paginate(pageNumber, pageSize, selectBuffer.toString(), sqlExceptSelectBuffer.toString());
    }

    public Company setId(Long id){
        return this.set("id",id);
    }

    public Long getId(){
        return this.get("id");
    }
        
    public Company setName(String name){
        return this.set("name",name);
    }

    public String getName(){
        return this.getStr("name");
    }
        
    public Company setCompanyCategoryId(Long companyCategoryId){
        return this.set("company_category_id", companyCategoryId);
    }

    public Long getCompanyCategoryId(){
        return this.get("company_category_id");
    }
        
    public Company setAddress(String address){
        return this.set("address",address);
    }

    public String getAddress(){
        return this.getStr("address");
    }
        
    public Company setRemark(String remark){
        return this.set("remark",remark);
    }

    public String getRemark(){
        return this.getStr("remark");
    }
}